package com.spsoft.core.aspect;

import com.alibaba.fastjson.JSONObject;
import com.spsoft.core.config.VmsProperties;
import com.spsoft.core.entity.VmsLog;
import com.spsoft.core.model.Result;
import com.spsoft.core.service.VmsLogService;
import com.spsoft.core.utils.SecurityUtils;
import com.spsoft.core.utils.ServletUtils;
import com.spsoft.core.utils.ThrowableUtil;
import lombok.extern.slf4j.Slf4j;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.annotation.AfterThrowing;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 *
 */
@Component
@Aspect
@Slf4j
public class LogAspect {

    public static Logger logger = LoggerFactory.getLogger(LogAspect.class);

    private final VmsLogService vmsLogService;

    private final VmsProperties vmsProperties;

    private final Environment environment;

    ThreadLocal<Long> currentTime = new ThreadLocal<>();

    public LogAspect(VmsLogService vmsLogService, VmsProperties vmsProperties, Environment environment) {
        this.vmsLogService = vmsLogService;
        this.vmsProperties = vmsProperties;
        this.environment = environment;
    }

    /**
     * 配置切入点
     */
    @Pointcut("@annotation(com.spsoft.core.annotation.Log)")
    public void logPointcut() {
        // 该方法无方法体,主要为了让同类中其他方法使用此切入点
    }

    /**
     * 配置环绕通知,使用在方法logPointcut()上注册的切入点
     *
     * @param joinPoint join point for advice
     */
    @Around("logPointcut()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result;
        currentTime.set(System.currentTimeMillis());
        result = joinPoint.proceed();
        long requestTime = System.currentTimeMillis() - currentTime.get();
        VmsLog log = new VmsLog("INFO", requestTime);
        currentTime.remove();
        HttpServletRequest request = ServletUtils.getHttpServletRequest();
        StringBuffer requestURL = request.getRequestURL();
        log.setRequestUrl(requestURL.toString());
        String currentUsername = null;
        Object response = result;
        try {
            currentUsername = SecurityUtils.getUsername();
            if (response instanceof Result) {
                String code = ((Result<?>) response).getCode();
                String message = ((Result<?>) response).getMessage();
                Map<String, String> map = new HashMap<>();
                map.put("code", code);
                map.put("message", message);
                log.setResponse(JSONObject.toJSONString(map));
            }
        } catch (Exception ignored) {
        }
        logger.info("登录账号：{}，请求URI：{}，时间：{}，耗时：{}ms", currentUsername, request.getRequestURI(), LocalDateTime.now(), requestTime);
        vmsLogService.save(currentUsername, ServletUtils.getBrowser(request), ServletUtils.getIpByRequest(request), joinPoint, log);
        return result;
    }

    /**
     * 配置异常通知
     *支持官网接口的异常日志记录
     * @param joinPoint join point for advice
     * @param e         exception
     */
    @AfterThrowing(pointcut = "logPointcut()", throwing = "e")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
        VmsLog log = new VmsLog("ERROR", System.currentTimeMillis() - currentTime.get());
        currentTime.remove();
        log.setExceptionDetail(ThrowableUtil.getStackTrace(e));
        HttpServletRequest request = ServletUtils.getHttpServletRequest();
        StringBuffer requestURL = request.getRequestURL();
        log.setRequestUrl(requestURL.toString());
        String currentUsername = null;
        String path = environment.getProperty("server.servlet.context-path");
        if (!vmsProperties.getIgnoreUrls().contains(request.getRequestURI().substring(path.length()))) {
            try {
                currentUsername = SecurityUtils.getUsername();
            } catch (Exception ignored) {
                logger.error("#########获取登录用户名失败");
            }
        } else {
            currentUsername = "对外接口";
        }
        vmsLogService.save(currentUsername, ServletUtils.getBrowser(request), ServletUtils.getIpByRequest(request), (ProceedingJoinPoint) joinPoint, log);
    }


}
